/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package med.movyzer.mobile.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import med.movyzer.mobile.R;
import med.movyzer.mobile.services.AccelService;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TwoLineListItem;
import android.widget.AdapterView.OnItemClickListener;

/**
 * This class provides a basic demonstration of how to write an Android
 * activity. Inside of its window, it places a single view: an EditText that
 * displays and edits some internal text.
 */
public class Movyzer extends Activity implements OnItemClickListener{

	private static final String NAME="name";
	private static final String DESC="desc";

	private ArrayList<String> mMenuText=new ArrayList<String>();
	private ArrayList<String> mMenuSummary=new ArrayList<String>();

	private TextView statusText;

	private int timerRate;


	/** Called with the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.movyzer);
		statusText = (TextView) findViewById(R.id.statustext);

		if(!isAccelSupported()){
			statusText.setText("Accelerometer not supported by this device!");
			return;
		}

		ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);  
		List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(1000);
		boolean serviceFound=false;
		for (int i=0; i<rs.size(); i++) {   
			ActivityManager.RunningServiceInfo  rsi = rs.get(i); 
			if(rsi.service.getClassName().equals("med.movyzer.mobile.services.AccelService")){
				//statusText.setText("Application logging!");
				mMenuText.add("Stop logging");
				mMenuSummary.add("stops logging the movements");
				mMenuText.add("Show stats");
				mMenuSummary.add("shows statistics for the current logging");
				serviceFound=true;
				break;
			}
		}  
		if(!serviceFound){
			//statusText.setText("Application <b>NOT</b> logging!");
			mMenuText.add("Start logging");
			mMenuSummary.add("starts logging the movements");
		}

		//mMenuText.add("Show chart");
		//mMenuSummary.add("shows a chart with all logged movements");
		mMenuText.add("close");
		mMenuSummary.add("closes program");


		ListView menu = (ListView) findViewById(R.id.mainmenu);
		menu.setOnItemClickListener(this);
		refreshListView();
	}

	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
	}

	private List<Map<String, String>> getListValues() {
		List<Map<String, String>> values = new ArrayList<Map<String, String>>();
		int length = mMenuText.size();
		for (int i = 0; i < length; i++) {
			Map<String, String> v = new HashMap<String, String>();
			v.put(Movyzer.NAME, mMenuText.get(i));
			v.put(Movyzer.DESC, mMenuSummary.get(i));
			values.add(v);
		}
		return values;
	}

	private void refreshListView(){
		ListView menu = (ListView) findViewById(R.id.mainmenu);
		//For custom lists create own row-xml-file and replace: android.R.layout.simple_list_item_2
		menu.setAdapter(new SimpleAdapter(this, getListValues(), android.R.layout.simple_list_item_2,
				new String[] { Movyzer.NAME, Movyzer.DESC }, new int[] { android.R.id.text1, android.R.id.text2 }));
	}

	private void setTimerRate(int rate){
		this.timerRate=rate;
		AccelService.service.startTimer(timerRate);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		Intent intent;
		TextView tview=(TextView) ((TwoLineListItem) v).getChildAt(0);
		String itemName=(String) tview.getText();
		if(itemName.equals("Start logging")){
			intent=new Intent(this,AccelService.class);
			this.startService(intent);
			@SuppressWarnings("unused")
			int timerRate=0;

			AlertDialog.Builder alert = new AlertDialog.Builder(this);   
			alert.setTitle("Input");   
			alert.setMessage("Please set the timer rate (ms)");   
			final EditText input = new EditText(this);   
			input.setText("1000");
			alert.setView(input);   
			alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {   
				public void onClick(DialogInterface dialog, int whichButton) {   
					@SuppressWarnings("unused")
					Editable value = input.getText();
					try{
						setTimerRate(Integer.parseInt(value.toString()));
					}catch (Exception e){
						Toast.makeText(getApplicationContext(), "ERROR: Timer rate set to 250", Toast.LENGTH_SHORT).show();
						setTimerRate(250);
					}
					Toast.makeText(getApplicationContext(), "Logging started", Toast.LENGTH_SHORT).show();
				}   
			});   
			alert.show();  
			

			mMenuText.remove(0);
			mMenuSummary.remove(0);
			mMenuText.add(0,"Show stats");
			mMenuSummary.add(0,"shows statistics for the current logging");
			mMenuText.add(0,"Stop logging");
			mMenuSummary.add(0,"stops logging the movements");
			refreshListView();
		}else if(itemName.equals("Stop logging")){
			Toast.makeText(getApplicationContext(), "Logging stopped\n Attention: Saving needs some time", Toast.LENGTH_SHORT).show();
			int result=AccelService.service.saveMovements();
			if(result==-1){
				Toast.makeText(getApplicationContext(), "ERROR: SD-Card not available or not writable", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplicationContext(), "File saved", Toast.LENGTH_SHORT).show();
			}

			intent=new Intent(this,AccelService.class);
			this.stopService(intent);


			mMenuText.remove(0);
			mMenuSummary.remove(0);
			mMenuText.remove(0);
			mMenuSummary.remove(0);
			mMenuText.add(0,"Start logging");
			mMenuSummary.add(0,"starts logging the movements");
			refreshListView();
		}else if(itemName.equals("Show stats")){
			intent = new Intent(this, StatsView.class);
			startActivity(intent);
		}else if(itemName.equals("close")){
			this.finish();
		}
	}

	public boolean isAccelSupported() {
		SensorManager mSensorEventManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
		Sensor mSensor = mSensorEventManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		if(mSensor!=null){
			return true;
		}
		return false;
	}

}
